<template>
	<view class="confirm-index">
		<view class="confirm-top">
			<view class="list-item">
				<view class="list-item-content">
					<view class="detail-box">
						<image :src="opt.pic"></image>
					</view>
					<view class="list-item-main">
						<view class="list-item-main-title">
							{{ opt.filmName }}
						</view>
						<view class="list-item-main-date text-t">
							<text class="mr-10">{{ opt.seats.length }}张</text>
							<text class="mr-10">{{ opt.time }}</text>
							<text class="mr-10">{{ opt.lv }}</text>
						</view>
						<view class="list-item-main-seat text-t">
							{{ opt.hallName }}
						</view>
						<view class="list-item-main-seat text-t">
							{{ opt.seats.join(',') }}
						</view>
						<view class="list-item-main-seat text-t">
							{{ opt.cinemaName }}
						</view>
					</view>
					<view style="display: inline-block;">
						<view class="time">
							<image class="time-icon" :src="static_url + '/static/img/clock.png'" mode=""></image>
							<view class="time-num">
								{{ time }}
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="list-item flex-box">
				<view class="confirm-pop-right">
					<image class="tanhao" src="/static/img/tanhao.png" mode=""></image>
					<view class="confirm-pop">
						<!-- <text>不可退票</text> -->
						<text>不可改签</text>
					</view>
				</view>
				<view class="confirm-pop-right" @click="open">
					<view class="confirm-pop-right-text">
						退改签须知
					</view>
					<image class="arrow-right" src="/static/img/arrowright.png" mode=""></image>
				</view>
			</view>
			<uni-popup ref="notice" class="pop" type="bottom">
				<view class="popup-box">
					<view class="popup-title">
						退签改签须知
					</view>
					<view class="popup-content">
						<!-- 	<view class="popup-fw mt-20">
							不可退票
						</view>
						<view class="popup-text mt-20">本影院不支持退票</view> -->
						<view class="popup-fw mt-20">
							不可改签
						</view>
						<view class="popup-text mt-20">本影院不支持改签</view>
						<view class="popup-fw mt-20">
							特别提醒
						</view>
						<view class="popup-text mt-20">付款后，非质量问题，不支持改签，请谨慎购买！</view>
					</view>
				</view>
			</uni-popup>
			<!-- <view class="list-item flex-box mt-20">
				<view class="confirm-pop-right">
					<image class="tanhao" src="/static/img/reg-tel.png" mode=""></image>
					<view class="confirm-pop">
						15013000784
					</view>
				</view>
			</view> -->
			<view class="list-item mt-20">
				<view class="notice">
					购票须知
				</view>
				<view class="notice-text">
					1.请确认购票场次和时间无误，购买成功后将不予更换
				</view>
				<view class="notice-text">
					2.因各影院取票系统设置存在差异，若正式影票上展示的价款及明细与在线购票展示的不一致，以您在线购票结算页面展示的内容为准
				</view>
				<view class="notice-text">
					3.由于不可抗力因素导致的场次取消或影院系统出票失败，会进行退款处理
				</view>
				<view class="notice-text">
					4.取票码可在“我的订单”查看
				</view>
			</view>
			<view class="list-item mt-20">
				<view class="discount-box">
					<view class="discount">
						和大优惠券
					</view>
					<view class="discount-right" @click="toDiscount">
						<text class="discount-text" v-if="selectedCount">已选择{{ selectedCount }}张兑换券</text>
						<text class="discount-text" v-else>待使用</text>
						<image class="img-icon" src="/static/img/arrowright.png" mode=""></image>
					</view>
				</view>
			</view>

		</view>
		<view class="bottombar">
			<view class="bottombar-left">
				<view class="bottom-num">
					共<text class="text-red">{{ opt.seats.length }}</text>张
				</view>
				<view class="bottom-price">
					合计：
					<text class="text-red fs-20">￥</text>
					<block v-if="selectedCount">
						<text class="text-red fw-700" style="text-decoration: line-through">{{ opt.price }}</text>
						<text class="text-red fw-700 fs-30">{{ opt.price - newPrice.toFixed(2) }}</text>
					</block>
					<block v-else>
						<text class="text-red fw-700">{{ opt.price }}</text>
					</block>
				</view>
			</view>
			<button :disabled="isSubmitting" class="op1" :style="'background:' + t('color1') + ''" form-type="submit"
				@click="getTmplIds">提交订单</button>
		</view>
	</view>
</template>

<script>
var app = getApp()
export default {
	data() {
		return {
			time: '5:00',
			timer: null,
			remainingTime: 300,
			opt: {},
			isSubmitting: false,
			highestPrice: '',
			lowestPrice: '',
			general: '',
			selectedId: null,
			selectedName: '',
			selectedCount: null,
			discount: '',
			newPrice: '',
			pre_url: app.globalData.pre_url, static_url: app.globalData.static_url,
		}
	},
	onLoad(opt) {
		if (opt) {
			const decodedParams = JSON.parse(decodeURIComponent(opt.params));
			this.opt = decodedParams
			const price = this.opt.seatsPrice.sort((a, b) => a - b);
			const highestPrice = Math.max(...price);
			const lowestPrice = Math.min(...price);
			this.highestPrice = highestPrice
			this.lowestPrice = lowestPrice
		}
		console.log(this.opt)
		this.startCountdown();

	},
	onShow() {
		// 监听子组件发出的事件
		uni.$on('receiveSelectedId', this.handleSelectedId);
	},
	beforeDestroy() {
		// 在组件销毁前，移除事件监听
		uni.$off('receiveSelectedId', this.handleSelectedId);
	},
	methods: {
		toDiscount() {
			const num = this.opt.seats.length;
			let url = `./coupon?num=${num}`;

			// 存在有效值时处理
			if (this.selectedId) {
				try {
					// 类型标准化（支持：数组/逗号字符串/单值）
					const ids = Array.isArray(this.selectedId) ?
						this.selectedId.map(String) :
						String(this.selectedId).split(',');

					// 过滤+去重
					const validIds = ids
						.map(id => id.trim())
						.filter(id => id && !isNaN(Number(id))); // 过滤非数字ID

					const uniqueIds = [...new Set(validIds)];

					// 添加参数
					if (uniqueIds.length > 0) {
						url += `&selectedId=${uniqueIds.join(',')}`;
					}
				} catch (e) {
					console.error('ID参数处理失败:', e);
				}
			}

			console.log('最终跳转URL:', url);
			uni.navigateTo({
				url
			});
		},
		// 处理接收到的 selectedId
		handleSelectedId(data) {

			console.log('接收到的选中的ID:', data.selectedId);
			console.log('接收到的兑换券名字:', data.selectedName);
			console.log('接收到的兑换券数量:', data.selectedCount);
			this.selectedId = [...new Set(data.selectedId.split(','))].join(','); // 更新 selectedId
			this.selectedName = data.selectedName; // 更新 couponName
			this.selectedCount = data.selectedCount;
			const price = this.opt.seatsPrice.sort((a, b) => a - b);
			let discount = this.selectedCount
			let selectedPrices = this.opt.seatsPrice.slice(0, discount);
			// 计算总共减去的价格
			let totalDiscount = selectedPrices.reduce((total, price) => total + price, 0);
			this.newPrice = totalDiscount
		},
		getTmplIds: function (e) {
			var that = this;

			// #ifdef MP-WEIXIN
			if (that.isSubmitting) return; // 如果正在提交，则不再处理
			that.isSubmitting = true;
			that.loading = true;
			app.get('Wxtmpl/getTmplIds', {
				type: 1
			}, function (res) {
				that.loading = false;

				var tmplIds = res.res;
				console.log(tmplIds);
				if (res.res) {

					wx.requestSubscribeMessage({
						tmplIds: tmplIds,
						complete(res, err) {
							that.submit();
							this.isSubmitting = false;
						}
					});

				} else {
					app.error(res);
					that.submit();
					this.isSubmitting = false;
				}

			});
			// #endif
			// #ifdef H5
			if (that.isSubmitting) return; // 如果正在提交，则不再处理
			that.isSubmitting = true;
			that.loading = false;

			that.submit();
			that.isSubmitting = false;
			// #endif
		},

		submit() {
			app.showLoading('提交订单中...');
			let that = this;
			app.post('film/createorder', {
				cinemaId: that.opt.cinemaId,
				title: that.opt.title,
				hallName: that.opt.hallName,
				showId: that.opt.showId,
				seats: that.opt.seats.join(','),
				changeSeat: that.opt.changeSeat,
				deliverMinute: that.opt.deliverMinute,
				singleCode: that.opt.singleCode,
				extra: null,
				pic: that.opt.pic,
				mycoupon_id: that.selectedId
			}, (res) => {
				if (res.status === 200) {
					app.showLoading(false);
					uni.showToast({
						title: '订单提交成功！',
						icon: 'success',
						duration: 2000,
						success: () => {
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/pay/pay?id=' + res.data
										.payorderid + '&tourl=' +
										'/pagesZone/movie/index'
								});
							}, 1000);
						}
					});
				} else {
					app.showLoading(false);
					app.error('订单提交失败:' + res.msg)
				}
				this.isSubmitting = false;
			});
		},
		open() {
			this.$refs.notice.open()
		},
		// 启动倒计时
		startCountdown() {
			this.timer = setInterval(() => {
				let minutes = Math.floor(this.remainingTime / 60);
				let seconds = this.remainingTime % 60;

				// 格式化时间
				let formattedTime = `${minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
				this.time = formattedTime;

				// 减少剩余时间
				if (this.remainingTime > 0) {
					this.remainingTime--;
				} else {
					clearInterval(this.timer); // 清除定时器
					this.redirectToPage(); // 倒计时结束后跳转页面		
				}
			}, 1000);
		},

		// 跳转到指定页面
		redirectToPage() {
			// uni.navigateTo({
			// 	url: '/pagesZone/movie/seats',
			// });
			uni.navigateBack()
		},
	},

	onUnload() {
		// 页面卸载时清除定时器
		clearInterval(this.timer);
	},
}
</script>

<style>
.confirm-index {
	padding: 20rpx;
}

.list-item {
	background-color: #fff;
	border-radius: 10rpx;
	padding: 20rpx;

}

.list-item-title {
	display: flex;
	justify-content: space-between;
	margin-bottom: 20rpx;
}

.detail-box {
	width: 160rpx;
	height: 240rpx;
	border-radius: 20rpx;
	overflow: hidden;
}

.detail-box image {
	width: 100%;
	height: 100%;
}

.list-item-content {
	display: flex;
}

.list-item-main {
	margin-left: 20rpx;
	flex: 1;
}


.text-t {
	color: #888;
	margin-top: 10rpx;
	font-size: 24rpx
}

.time {
	color: #007aff;
	font-size: 24rpx;
	display: flex;
	align-items: center;
}

.time-icon {
	width: 24rpx;
	height: 24rpx;
}

.time-num {
	margin-left: 10rpx;
}

.flex-box {
	display: flex;
	justify-content: space-between;
}

.confirm-pop {
	color: #666;
}

.arrow-right {
	width: 28rpx;
	height: 28rpx;
}

.confirm-pop-right {
	display: flex;
	align-items: center;
}

.confirm-pop-right-text {
	font-size: 24rpx;
	color: #aaa;
}

.tanhao {
	width: 40rpx;
	height: 40rpx;
}

.mt-20 {
	margin-top: 20rpx;
}

.notice {
	font-weight: 700;
	color: #000000;
}

.notice-text {
	font-size: 26rpx;
	line-height: 1.8;
	color: #666;
	margin-top: 10rpx;
}

.bottombar {
	width: 94%;
	position: fixed;
	bottom: 0px;
	left: 0px;
	background: #fff;
	display: flex;
	height: 100rpx;
	padding: 0 4% 0 4%;
	align-items: center;
	box-sizing: content-box
}

.bottombar-left {
	flex: 1;
	display: flex;
	align-items: center;
}

.op1 {
	width: 200rpx;
	height: 80rpx;
	line-height: 80rpx;
	color: #fff;
	background-color: rgb(235, 84, 77);
	text-align: center;
	font-size: 30rpx;
	border-radius: 44rpx
}

.text-red {
	color: rgb(235, 84, 77);
}

.fs-20 {
	font-size: 24rpx;
}

.fs-30 {
	font-size: 40rpx
}

.fw-700 {
	font-weight: 700;
}

.uni-popup__wrapper-box {
	background-color: #fff;
}

.popup-box {
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0;
	position: relative;
}

.popup-title {
	padding: 40rpx 0;
	text-align: center;
	border-bottom: 1px solid #E3E3E3;
	font-weight: 600;
	color: #666;
}

.popup-content {
	padding: 52rpx;
}

.popup-fw {
	font-size: 38rpx;
	font-weight: 600;
}

.popup-text {
	color: #666;
	font-size: 24rpx;
}

.bottom-num {
	margin-right: 10rpx;
}

.mr-10 {
	display: block;
}

.discount-box {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.discount-right {
	display: flex;
	align-items: center;
}

.discount-text {
	color: #e92416;
}

.img-icon {
	width: 40rpx;
	height: 40rpx;
}
</style>